<?php

/**
 * Description of Article Controller
 *
 * @author Vu
 */

class Admin_Cms_NewsletterController extends My_Controller_Action {
	
	public function init(){
		parent::init();
		
		$auth = Zend_Auth::getInstance();
        
        if(!$auth->hasIdentity())
        { 
            $this->_redirect("user/account/login");
        }
        
        if ($this->isAccess($auth->getIdentity()->group_id, 6))
        {
			//to do
		} else {
            die("Access denied");
        }
	}   
	
	public function indexAction() {
		$this->view->rightAdminModules('right');
		
		$this->view->by = $this->_request->getParam("by", "a.newsletter_id");
        $this->view->order = $this->_request->getParam("order", "desc");
		
		$query = "	SELECT a.newsletter_id, a.email, b.name as name
					FROM cms_newsletter as a LEFT JOIN cms_category as b
					ON a.category_id = b.category_id
					ORDER BY {$this->view->by} {$this->view->order}";
		$tb = Zend_Db_Table::getDefaultAdapter();
        $tb->setFetchMode(Zend_Db::FETCH_OBJ);
        $this->view->listEmail = $tb->fetchAll($query);
    }
	
	public function deleteAction() {
		$id = $this->_request->getParam('id');
		$model = $this->loadModel('admin_cms','Newsletter');
		$row = $model->fetchRow($model->select()->where('newsletter_id=?',$id));
		$row->delete();
		$this->_redirect($this->view->baseUrl('index.php/admin_cms/newsletter'), array());
    }
	
	public function prepareAction(){
		$this->view->rightAdminModules('right');
		$this->view->CKEditorScript = $this->view->setupCKEditor('content');
		$model = $this->loadModel('admin_cms','Category');
		$this->view->categories = $model->fetchAll($model->select());
	}
	
	public function sendAction(){
		$category_id = $this->_request->getParam('category_id');
		$subject = $this->_request->getParam('subject');
		$content = $this->_request->getParam('content');
		
		$model = $this->loadModel('admin_cms','Newsletter');
		$rows = $model->fetchAll($model->select());
		
		foreach($rows as $row){
			$tmp = $row->category_id;
			$email = $row->email;
			if($tmp == $category_id || $tmp == 0){
				$mail = new Zend_Mail();
				//$mail->setBodyText('My Nice Test Text');
				$mail->setBodyHtml($content);
				$mail->setFrom('newsletter@hopmua.com', 'Hopmua newsletter');
				$mail->addTo($email, 'Guest');
				$mail->setSubject($subject);
				$mail->send();
			}
		}
		$this->_redirect($this->view->baseUrl('index.php/admin_cms/newsletter'), array());
		exit;
	}
}
